import request from '@/utils/request.js'

/**
 * json对象的path转换成变量
 * 如{student:{name:'xxx',age:21}}
 * pathStr 例如 student.name
 */
const getPathRef = (origin, pathStr) => {
	let path = [];
	if (typeof(pathStr) == 'string') path = pathStr.split('.');
	
	let target = null;
	path.forEach((item) => {
		if(!target) {
			target = origin[path[0]];
		} else {
			target = target[item];
		}
	});
	
	return target;
}

const preViewImage = (images) => {
	uni.previewImage({
		urls: images
	})
}

//选择图片
const chooseImage = (path, that) => {
	uni.chooseImage({
		count: 9, //默认9
		sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有				     
		success: function(res) {
			uploadImg(res.tempFiles, path, that)
		}
	});
};

//上传图片
const uploadImg = (data, path, that)=> {
	uni.showLoading({})
	var i = data.i ? data.i : 0; //当前上传的哪张图片
	var success = data.success ? data.success : 0; //上传成功的个数
	var fail = data.fail ? data.fail : 0; //上传失败的个数
	uni.uploadFile({
		url: request.http + "/h5/order.upload/doupload",
		filePath: data[i].path,
		header: {},
		name: 'file',
		formData: {
			token: uni.getStorageSync("token") ? uni.getStorageSync("token") : ''
		},
		success: (res) => {
			
			if (JSON.parse(res.data).msg == "上传成功") {
				success++; //图片上传成功，图片上传成功的变量+1
				uni.hideLoading()
			}
			
			let target = getPathRef(that, path);
			target.push(JSON.parse(res.data).data.url)
		},
		fail: () => {
			fail++; //图片上传失败，图片上传失败的变量+1
		},
		complete: () => {
			i++; //这个图片执行完上传后，开始上传下一张
			if (i == data.length) { //当图片传完时，停止调用          
				uni.showToast({
					icon: 'none',
					title: '成功：' + success + " 失败：" + fail,
				})
			} else { //若图片还没有传完，则继续调用函数
				data.i = i;
				data.success = success;
				data.fail = fail;
				uploadImg(data, path, that);
			}
		}
	})
}

//删除图片
const deleteImage = (index, path, that) => {
	let target = getPathRef(that, path);
	target.splice(index, 1);
}

module.exports = {
	preViewImage: preViewImage,
	chooseImage: chooseImage,
	uploadImg: uploadImg,
	deleteImage:deleteImage
}
